package com.cgtong.android.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.bean.SimpleResult;
import com.cgtong.android.http.ApiManager;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.ReportProblemContract;
import com.cgtong.android.mvp.presenter.ReportProblemPresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.util.TakePhotoHelper;
import com.cgtong.android.widget.BaseDialog;
import com.cgtong.android.widget.GlideApp;
import com.cgtong.android.widget.audio.AudioPlayManager;
import com.cgtong.android.widget.audio.AudioRecordManager;
import com.cgtong.android.widget.audio.IAudioPlayListener;
import com.cgtong.android.widget.audio.IAudioRecordListener;
import com.cgtong.android.widget.matisse.Matisse;
import com.cgtong.android.widget.matisse.MimeType;
import com.cgtong.android.widget.matisse.engine.impl.GlideEngine;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jph.takephoto.uitl.TConstant;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.IProgressDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * 问题上报
 * by zhuqingchun
 */

public class ReportProblemActivity extends BaseTitleActivity implements TakePhoto.TakeResultListener, InvokeListener, ReportProblemContract.View {


    private static final String TAG = ReportProblemActivity.class.getName();

    public static final int KEY_CODE_FOR_REQUEST = 22;
    public static final int KEY_CODE_FOR_RESULT = 23;

    private static final int REQUEST_CODE_CHOOSE = 24;

    private static final String KEY_EDIT_MODEL = "edit_model";
    private static final String KEY_PROBLEM_BEAN = "problem_bean";
    public static final String KEY_ITEM_POS = "item_pos";
    public static final String KEY_COMMIT_DRAFT = "commit_draft";

    @BindView(R.id.report_problem_area_fl)
    FrameLayout mReportProblemAreaFl;
    @BindView(R.id.lead_explain_fl)
    FrameLayout mLeadExplainFl;
    @BindView(R.id.write_left_txt)
    TextView mWriteLeftTxt;
    @BindView(R.id.write_left_fl)
    FrameLayout mWriteLeftFl;
    @BindView(R.id.record_right_txt)
    TextView mRecordRightTxt;
    @BindView(R.id.record_right_fl)
    FrameLayout mRecordRightFl;
    @BindView(R.id.describe_problem_edt)
    EditText mDescribeProblemEdt;
    @BindView(R.id.play_audio_img)
    TextView mPlayAudioTxt;
    @BindView(R.id.play_audio_rl)
    RelativeLayout mPlayAudioRl;
    @BindView(R.id.duration_txt)
    TextView mDurationTxt;
    @BindView(R.id.record_txt)
    TextView mRecordTxt;
    @BindView(R.id.audio_rl)
    FrameLayout mAudioRl;
    @BindView(R.id.your_location_txt)
    TextView mYourLocationTxt;
    @BindView(R.id.your_location_rl)
    RelativeLayout mYourLocationRl;
    @BindView(R.id.whether_public_txt)
    TextView mWhetherPublicTxt;
    @BindView(R.id.whether_public_rl)
    RelativeLayout mWhetherPublicRl;
    @BindView(R.id.save_draft_txt)
    TextView mSaveDraftTxt;
    @BindView(R.id.commit_problem_txt)
    TextView mCommitProblemTxt;
    @BindView(R.id.root_ll)
    LinearLayout mRootLl;
    @BindView(R.id.left_num_txt)
    TextView mLeftNumTxt;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.add_picture_img)
    ImageView mAddPictureImg;


    private List<String> mCompressList;
    private InvokeParam invokeParam;
    private PictureAdapter mAdapter;
    private List<ProblemBean.ResourceBean> mImgList;
    private List<ProblemBean.ResourceBean> mLocationImgList;//编辑模式使用

    //因为拍完照之后，需要压缩，再加水印，然后再压缩这一过程，需要花费时间，
    //所以这个集合用户判断图片大小
    private List<String> mFakeImgList;

    //    private Set<ProblemBean.ResourceBean> mImgSet;
    private TakePhoto mTakePhoto;
    private ReportProblemPresenter mPresenter;
    private TakePhotoHelper mTakeHelper;
    private boolean isWriteMode = true;//true：文字模式 false:语音模式

    //提交所需参数
    private String mDesc;//描述
    private String mAddress;//地址，除非是草稿，不然不可为空
    private double mLng;//纬度，除非是草稿，不然不可为空
    private double mLat;//经度，除非是草稿，不然不可为空
    private int mIsDraft = 1;//是否草稿，1，是，0不是
    private int mIsOpen = 1;//是否公开，1，公开，0不公开
    private List<File> mImgFiles = new ArrayList<>();//1-3张图片数组，除非是草稿，不然不可为空
    private File mPosFile;//位置图片，除非是草稿，不然不可为空
    private File mVoiceFile;//音频文件，除非是草稿，不然不可为空
    private int mVoiceTime;//录音时长

    //用来恢复草稿
    private boolean isEditProblem = true;//true:编辑草稿 false:添加新问题
    private ProblemBean mProblemBean;

    private Disposable mDisposable;//取消请求用到
    //草稿提交后,草稿箱页移除的位置
    private int mPosition;
    private int numberOfImagesToSelect = 0;


    public static void startForResult(Activity activity, boolean isEditProblem, ProblemBean problemBean, int itemPosition) {
        Intent starter = new Intent(activity, ReportProblemActivity.class);
        starter.putExtra(KEY_EDIT_MODEL, isEditProblem);
        starter.putExtra(KEY_PROBLEM_BEAN, problemBean);
        starter.putExtra(KEY_ITEM_POS, itemPosition);
        activity.startActivityForResult(starter, KEY_CODE_FOR_REQUEST);
    }


    private ProgressDialog dialog;
    private IProgressDialog mProgressDialog = new IProgressDialog() {
        @Override
        public Dialog getDialog() {
            if (dialog == null) {
                dialog = new ProgressDialog(ReportProblemActivity.this);
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
                dialog.setMessage("正在提交...");
                // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
//                dialog.setTitle("文件上传");
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        LogUtils.d("取消请求一次");
                        EasyHttp.cancelSubscription(mDisposable);
                    }
                });
//                dialog.setMax(100);
            }
            return dialog;
        }
    };

    @Override
    protected String getContentTitle() {
        return getString(R.string.title_report_problem);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_report_problem;
    }

    @Override
    protected void loadDataByNet() {
        isEditProblem = getIntent().getBooleanExtra(KEY_EDIT_MODEL, false);
        mProblemBean = getIntent().getParcelableExtra(KEY_PROBLEM_BEAN);
        mPosition = getIntent().getIntExtra(KEY_ITEM_POS, -1);
        PostUtil.postSuccessDelayed(loadService);
        mPresenter = new ReportProblemPresenter(this);
        initAudioRecordManager();
        initPictureManager();
        //录音监听
        mRecordTxt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (ContextCompat.checkSelfPermission(ReportProblemActivity.this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                            AudioPlayManager.getInstance().stopPlay();//停止播放
                            AudioRecordManager.getInstance(ReportProblemActivity.this).startRecord();
                        } else {
                            doRecordByPermission();
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (isCancelled(v, event)) {
                            AudioRecordManager.getInstance(ReportProblemActivity.this).willCancelRecord();
                        } else {
                            AudioRecordManager.getInstance(ReportProblemActivity.this).continueRecord();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        AudioRecordManager.getInstance(ReportProblemActivity.this).stopRecord();
                        AudioRecordManager.getInstance(ReportProblemActivity.this).destroyRecord();
                        break;
                }
                return false;
            }
        });

        //输入文字监听
        mDescribeProblemEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String filterStr = s.toString().replaceAll(" ", "");
                if (TextUtils.isEmpty(filterStr)) {
                    mLeftNumTxt.setText(getString(R.string.txt_filter_default));
                    return;
                }
                mLeftNumTxt.setText(filterStr.length() + "/500");
            }
        });

        //长按播放案件，弹出删除提示
//        final DeletePopupWindow deletePopupWindow = new DeletePopupWindow(this);
//        deletePopupWindow.setClickListener(new DeletePopupWindow.OnClickListener() {
//            @Override
//            public void onClick() {
//                showDeleteRecordDialog();
//
//            }
//        });
        mPlayAudioRl.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                deletePopupWindow.showPopupWindow(v);
                showDeleteRecordDialog();
                return true;
            }
        });

        if (isEditProblem) {
            showMyDraft();
        }

        mTakeHelper = new TakePhotoHelper();
        mCompressList = new ArrayList<>();

    }


    private boolean isCancelled(View view, MotionEvent event) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        if (event.getRawX() < location[0] || event.getRawX() > location[0] + view.getWidth() || event.getRawY() < location[1] - 40) {
            return true;
        }
        return false;
    }

    /**
     * 从草稿箱进入展示
     */
    private void showMyDraft() {
        LogUtils.d("showMyDraft = " + mProblemBean.toString());
        //描述-------------------
        String draftDesc = mProblemBean.getDesc();
        if (!TextUtils.isEmpty(draftDesc)) {
            mDescribeProblemEdt.setText(draftDesc);
            mDescribeProblemEdt.setSelection(draftDesc.length());
        }
        //语音
        if (!TextUtils.isEmpty(mProblemBean.getVoiceUrl()) && mProblemBean.getVoiceUrl().startsWith("http:")) {
            if (TextUtils.isEmpty(draftDesc)) {
                onViewClicked(mRecordRightFl);
            }
            //播放录音按钮
            mPlayAudioRl.setVisibility(View.VISIBLE);
            mPlayAudioTxt.setVisibility(View.VISIBLE);
            //录音时间
            mDurationTxt.setVisibility(View.VISIBLE);
            mVoiceTime = mProblemBean.getVoiceTime();
            mDurationTxt.setText(mVoiceTime + "\"");
            ViewGroup.LayoutParams layoutParams = mPlayAudioRl.getLayoutParams();
            layoutParams.width = (int) getResources().getDimension(R.dimen.size_width_play_audio);
            mPlayAudioRl.setLayoutParams(layoutParams);
            mPlayAudioRl.setBackgroundDrawable(ContextCompat.getDrawable(ReportProblemActivity.this, R.drawable.bg_audio_gray));
            mPlayAudioRl.setPadding((int) getResources().getDimension(R.dimen.padding_left_play_audio), 0, 0, 0);
            mPlayAudioTxt.setText("");
            mPlayAudioTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(ReportProblemActivity.this, R.drawable.ic_trumpet), null, null, null);
            mRecordTxt.setText(getString(R.string.txt_record_again));

        }
        //是否公开-------------------
        if (mProblemBean.getIsOpen() == 1) {
            mWhetherPublicTxt.setText(getString(R.string.txt_public));
            mIsOpen = 1;
        } else {
            mWhetherPublicTxt.setText(getString(R.string.txt_not_public));
            mIsOpen = 0;
        }
        //现场图片-------------------
//        mAddPictureImg.setVisibility(View.GONE);//添加图片按钮隐藏

        if (mProblemBean.getResourceList() != null && mProblemBean.getResourceList().size() > 0) {
            LogUtils.d("图片是否课件 = " + (mRecyclerView.getVisibility() == View.VISIBLE));
            numberOfImagesToSelect = mProblemBean.getResourceList().size();
            LogUtils.d("select", "numberOfImagesToSelect: " + numberOfImagesToSelect);
            downloadResourceImg();
//            mImgList.addAll(mProblemBean.getResourceList());
//            mAdapter.notifyItemRangeInserted(0, mImgList.size() - 1);
        }
        //地址-------------------
        mYourLocationTxt.setText(mProblemBean.getAddress());
        mAddress = mProblemBean.getAddress();
        mLng = mProblemBean.getLng();
        mLat = mProblemBean.getLat();


        //位置图片-------------------
        String localImgUrl = mProblemBean.getLocalImgUrl();
        if (!TextUtils.isEmpty(localImgUrl)) {
            String localImgName = localImgUrl.substring(localImgUrl.lastIndexOf("/") + 1, localImgUrl.length());
            LogUtils.d("localImgName= " + localImgName);
            File imgDir = new File(ConstantManager.LOCATION_PHOTO_SAVE_DIR);
            LogUtils.d("imgDir = " + imgDir.getAbsolutePath());
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            String localImgPath = imgDir + "/" + localImgName;
            LogUtils.d("localImgPath == " + localImgPath);

            mPosFile = new File(localImgPath);
            if (!mPosFile.exists()) {
                downloadLocalImg(localImgName);
            }
        }

        //语音-------------------
        String voiceDownloadUrl = mProblemBean.getVoiceUrl();
        if (!TextUtils.isEmpty(voiceDownloadUrl)) {
            String voiceFileName = voiceDownloadUrl.substring(voiceDownloadUrl.lastIndexOf("/") + 1, voiceDownloadUrl.length());
            LogUtils.d("voiceFileName = " + voiceFileName);
            File audioDir = new File(ConstantManager.AUDIO_SAVE_DIR);
            LogUtils.d("audioDir = " + audioDir.getAbsolutePath());
            if (!audioDir.exists()) {
                audioDir.mkdirs();
            }
            String voiceFilePath = audioDir + "/" + voiceFileName;
            LogUtils.d("voiceFilePath == " + voiceFilePath);

            mVoiceFile = new File(voiceFilePath);
            if (!mVoiceFile.exists()) {
                downloadVoice(voiceFileName, false);
            }
        }


    }


    /**
     * 保存到草稿箱or提交
     */
    private void doCommitProblem(boolean isSaveDraft, boolean isConfirmAgain) {
        if (isSaveDraft) {//点击保存到草稿箱
            mIsDraft = 1;
            mDesc = mDescribeProblemEdt.getText().toString().replaceAll(" ", "");
        } else { //点击提交
            mIsDraft = 0;
            //文字
            mDesc = mDescribeProblemEdt.getText().toString().replaceAll(" ", "");
            if (TextUtils.isEmpty(mDesc) && mVoiceFile == null) {
                ToastUtils.showShort(getString(R.string.txt_content_is_null));
                return;
            }
        }

        //现场图片
//        mImgSet.clear();
        mImgFiles.clear();
//        if (isEditProblem) {
//            if (mImgList.size() == mProblemBean.getResourceList().size()) {
//                mImgSet.addAll(mImgList);//去重
//                for (ProblemBean.ResourceBean bean : mImgSet) {
//                    File file = new File(bean.getContent());
//                    mImgFiles.add(file);
//                }
//            } else {
//                ToastUtils.showShort(getString(R.string.txt_picture_is_loading));
//                return;
//            }
//        } else {
        if (mImgList.size() > 0) {
//            mImgSet.addAll(mImgList);//去重
            for (ProblemBean.ResourceBean bean : mImgList) {
                File file = new File(bean.getContent());
                mImgFiles.add(file);
            }
        } else {
            ToastUtils.showShort(getString(R.string.txt_picture_is_null));
            return;
//            }
        }

        //地址
        if (mPosFile == null) {
            ToastUtils.showShort(getString(R.string.txt_address_is_null));
            return;
        }
        if (isConfirmAgain) {
            showCommitDialog(isSaveDraft);
        } else {
            //调取接口
            long problemId = -1;
            if (isEditProblem) {
                problemId = mProblemBean.getId();
            }
            initDialog(isSaveDraft);
            mDisposable = mPresenter.httpCommitReport(problemId, mDesc, mAddress, mLng
                    , mLat, mIsDraft, mIsOpen, mImgFiles, mPosFile, mVoiceFile, mVoiceTime, mProgressDialog);
        }
    }

    private void initDialog(boolean isSaveDraft) {
        dialog = new ProgressDialog(ReportProblemActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        if (isSaveDraft) {
            dialog.setMessage("正在保存...");
        } else {
            dialog.setMessage("正在提交...");
        }
        // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
//                dialog.setTitle("文件上传");
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                LogUtils.d("取消请求一次");
                EasyHttp.cancelSubscription(mDisposable);
            }
        });
    }


    /**
     * 删除录音提示
     */
    private void showDeleteRecordDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_delete_record)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        view.findViewById(R.id.not_save_record_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPlayAudioRl.setVisibility(View.GONE);
                                mDurationTxt.setVisibility(View.GONE);
                                AudioPlayManager.getInstance().stopPlay();//停止播放
                                dialog.cancel();
                                if (mVoiceFile.exists()) {
                                    mVoiceFile.delete();
                                }
                                mVoiceFile = null;
                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    /**
     * 初始化现场拍照图片列表
     */
    private void initPictureManager() {
        mImgList = new ArrayList<>();
        mLocationImgList = new ArrayList<>();
        mFakeImgList = new ArrayList<>();
//        mImgSet = new HashSet<>();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mAdapter = new PictureAdapter(mImgList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delete_img) {
                    mImgList.remove(position);
                    mFakeImgList.remove(position);
                    mAdapter.notifyItemRemoved(position);
                    numberOfImagesToSelect = mImgList.size();
                    LogUtils.d("select", "numberOfImagesToSelect: " + numberOfImagesToSelect);

                    if (mImgList.size() == 0) {
                        mRecyclerView.setVisibility(View.GONE);
//                        mAdapter.setShowDelete(false);
                    } else if (mImgList.size() < 3) {
                        mAddPictureImg.setVisibility(View.VISIBLE);
                    }
                } else if (view.getId() == R.id.preview_img) {
                    LocalImagePreviewActivity.start(ReportProblemActivity.this, mImgList, position);
                }

            }
        });

    }


    @Override
    public void onError(ApiException e) {
        ToastUtils.showShort(e.getMessage());
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void onHttpCommitReportSuccess(SimpleResult simpleResult) {
        ToastUtils.showShort(simpleResult.getMsg());
        if (simpleResult.getCode() == 0) {
            if (dialog != null) {
                dialog.dismiss();
            }
            Intent intent = new Intent();
            if (mIsDraft == 1) {//保存草稿成功，返回草稿箱，再次请求数据
                intent.putExtra(KEY_COMMIT_DRAFT, true);
            }
            intent.putExtra(KEY_ITEM_POS, mPosition);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private class PictureAdapter extends BaseQuickAdapter<ProblemBean.ResourceBean, BaseViewHolder> {
        boolean isShowDelete = true;

        public PictureAdapter(@Nullable List<ProblemBean.ResourceBean> data) {
            super(R.layout.adapter_preview, data);
        }

        public void setShowDelete(boolean isShow) {
            this.isShowDelete = isShow;
            notifyDataSetChanged();
        }

//        public void hideDelete() {
//            if (isShowDelete) {
//                isShowDelete = false;
//                notifyDataSetChanged();
//            }
//        }

//        public void showDelete() {
//            if (!isShowDelete)
//                isShowDelete = true;
//            else
//                isShowDelete = false;
//            notifyDataSetChanged();
//        }

        @Override
        protected void convert(final BaseViewHolder helper, ProblemBean.ResourceBean item) {
            ImageView previewImg = helper.getView(R.id.preview_img);
            GlideApp.with(ReportProblemActivity.this).load(item.getContent()).fitCenter().into((previewImg));
//            if (isShowDelete) {
//                helper.setVisible(R.id.delete_img, true);
//            } else {
//                helper.setVisible(R.id.delete_img, false);
//            }
            helper.setVisible(R.id.delete_img, isShowDelete);

//            previewImg.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    if (isEditProblem) {
////                        ToastUtils.showShort(getString(R.string.txt_not_modify_location));
//                        return false;
//                    }
//                    showDelete();
//                    return false;
//                }
//            });
            helper.addOnClickListener(R.id.delete_img);
            helper.addOnClickListener(R.id.preview_img);

        }
    }


    /**
     * 获取录音权限
     */
    private void doRecordByPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.RECORD_AUDIO)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
//                            AudioPlayManager.getInstance().stopPlay();//停止播放
//                            AudioRecordManager.getInstance(ReportProblemActivity.this).startRecord();

                        } else {
                            ToastUtils.showLong(R.string.permission_request_denied);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    protected void onDataReloadByNet(View v) {

    }


    @Override
    protected void onPause() {
        super.onPause();
        AudioPlayManager.getInstance().stopPlay();//停止播放
    }

    /**
     * 初始化录音组件
     */
    private void initAudioRecordManager() {
        AudioRecordManager.getInstance(this).setMaxVoiceDuration(ConstantManager.DEFAULT_MAX_AUDIO_RECORD_TIME_SECOND);
        File audioDir = new File(ConstantManager.AUDIO_SAVE_DIR);
        if (!audioDir.exists()) {
            audioDir.mkdirs();
        }
        AudioRecordManager.getInstance(this).setAudioSavePath(audioDir.getAbsolutePath());
        AudioRecordManager.getInstance(this).setAudioRecordListener(new IAudioRecordListener() {
            private TextView msgTxt;
            private ImageView stateImg;
            private ImageView cancelImg;
            private RelativeLayout stateRl;
            private TextView countDownTxt;
            private PopupWindow popupWindow;

            @Override
            public void initTipView() {
                View view = View.inflate(ReportProblemActivity.this, R.layout.layout_popup_audio, null);
                msgTxt = (TextView) view.findViewById(R.id.vol_msg_txt);
                stateImg = (ImageView) view.findViewById(R.id.vol_img);
                cancelImg = (ImageView) view.findViewById(R.id.cancel_send_img);
                stateRl = (RelativeLayout) view.findViewById(R.id.microphone_rl);
                countDownTxt = (TextView) view.findViewById(R.id.count_down_txt);
                popupWindow = new PopupWindow(view, -1, -1);
                popupWindow.showAtLocation(mRootLl, Gravity.CENTER, 0, 0);
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(false);
                popupWindow.setTouchable(false);


            }

            @Override
            public void setTimeoutTipView(int counter) {
                LogUtils.d("counter = " + counter);
                this.stateRl.setVisibility(View.GONE);
                this.cancelImg.setVisibility(View.GONE);
                this.countDownTxt.setVisibility(View.VISIBLE);
                this.countDownTxt.setText(counter + "");
            }

            @Override
            public void setRecordingTipView() {
                if (this.popupWindow != null) {
                    this.stateRl.setVisibility(View.VISIBLE);
                    this.cancelImg.setVisibility(View.GONE);
                    this.countDownTxt.setVisibility(View.GONE);
                    this.stateImg.setImageResource(R.drawable.toast_vol_1);
                    this.msgTxt.setText(getString(R.string.txt_before_cancel_send));
                }
            }

            @Override
            public void setAudioShortTipView() {
                if (this.popupWindow != null) {
                    this.stateRl.setVisibility(View.GONE);
                    this.cancelImg.setVisibility(View.VISIBLE);
                    this.countDownTxt.setVisibility(View.GONE);
                    this.cancelImg.setImageResource(R.drawable.toast_timeshort);
                    this.msgTxt.setText(getString(R.string.voice_short));
                }
            }

            @Override
            public void setCancelTipView() {
                if (this.popupWindow != null) {
                    this.stateRl.setVisibility(View.GONE);
                    this.cancelImg.setVisibility(View.VISIBLE);
                    this.countDownTxt.setVisibility(View.GONE);
                    this.msgTxt.setText(getString(R.string.txt_cancel_send));

                }
            }

            @Override
            public void destroyTipView() {
                if (this.popupWindow != null) {
                    this.popupWindow.dismiss();
                    this.popupWindow = null;
                    this.stateImg = null;
                    this.cancelImg = null;
                    this.msgTxt = null;
                    this.stateRl = null;
                    this.countDownTxt = null;
                }


                mRecordTxt.setBackgroundDrawable(ContextCompat.getDrawable(ReportProblemActivity.this, R.drawable.bg_record_again));
                mRecordTxt.setText(getString(R.string.txt_record_again));

            }

            @Override
            public void onStartRecord() {
                mRecordTxt.setBackgroundDrawable(ContextCompat.getDrawable(ReportProblemActivity.this, R.drawable.bg_big_record));
                mRecordTxt.setText(getString(R.string.txt_recording));
            }

            @Override
            public void onFinish(Uri audioPath, int duration) {
                //发送文件
                File file = new File(audioPath.getPath());
                LogUtils.d("onFinish ============ " + file.getAbsolutePath());
                if (file.exists()) {
                    //播放录音按钮
                    mPlayAudioRl.setVisibility(View.VISIBLE);
                    mPlayAudioTxt.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams layoutParams = mPlayAudioRl.getLayoutParams();
                    layoutParams.width = (int) getResources().getDimension(R.dimen.size_width_play_audio);
                    mPlayAudioRl.setLayoutParams(layoutParams);
                    mPlayAudioRl.setBackgroundDrawable(ContextCompat.getDrawable(ReportProblemActivity.this, R.drawable.bg_audio_gray));
                    mPlayAudioRl.setPadding((int) getResources().getDimension(R.dimen.padding_left_play_audio), 0, 0, 0);
                    mPlayAudioTxt.setText("");
                    mPlayAudioTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(ReportProblemActivity.this, R.drawable.ic_trumpet), null, null, null);
                    //录音时间
                    mDurationTxt.setVisibility(View.VISIBLE);
                    mDurationTxt.setText(duration + "\"");
                    //录音文件路径
                    mVoiceFile = new File(file.getAbsolutePath());
                    //录音时长
                    mVoiceTime = duration;
                }
            }

            @Override
            public void onAudioDBChanged(int db) {
                if (this.popupWindow != null) {
                    switch (db / 6) {
                        case 0:
                            this.stateImg.setImageResource(R.drawable.toast_vol_1);
                            break;
                        case 1:
                            this.stateImg.setImageResource(R.drawable.toast_vol_2);
                            break;
                        case 2:
                            this.stateImg.setImageResource(R.drawable.toast_vol_3);
                            break;
                        case 3:
                            this.stateImg.setImageResource(R.drawable.toast_vol_4);
                            break;
                        case 4:
                            this.stateImg.setImageResource(R.drawable.toast_vol_5);
                            break;
                        case 5:
                            this.stateImg.setImageResource(R.drawable.toast_vol_6);
                            break;
                        default:
                            this.stateImg.setImageResource(R.drawable.toast_vol_7);
                    }
                }
            }
        });
    }


    @OnClick({R.id.report_problem_area_fl, R.id.lead_explain_fl, R.id.write_left_fl, R.id.record_right_fl, R.id.play_audio_rl, R.id.record_txt, R.id.your_location_rl, R.id.whether_public_rl, R.id.save_draft_txt, R.id.commit_problem_txt, R.id.add_picture_img
            , R.id.title_left_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_txt:
                showBackDialog();
                break;
            case R.id.report_problem_area_fl:
                //Intent explainIntent = new Intent(this, QuestionClassifyActivity.class);
                //this.startActivity(explainIntent);
                WebViewActivity.actionStart(this, ApiManager.PROBLEM_SBFW_URL);
                break;
            case R.id.lead_explain_fl:
                //Intent reportIntent = new Intent(this, ReportInstructionActivity.class);
                //this.startActivity(reportIntent);
                WebViewActivity.actionStart(this, ApiManager.PROBLEM_YDSM_URL);
                break;
            case R.id.write_left_fl://选择输入文字
                isWriteMode = true;
                //清空语音
//                mPlayAudioTxt.setText(getString(R.string.txt_hint_describe_problem));
//                mPlayAudioTxt.setPadding(0, 0, 0, 0);
//                mPlayAudioTxt.setBackgroundDrawable(null);
//                mPlayAudioTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//                mDurationTxt.setVisibility(View.GONE);
//                if(mDurationTxt.getTag()!=null){
//                    mDurationTxt.setTag(null);
//                }
//                mRecordTxt.setText(getString(R.string.txt_start_record));


                AudioPlayManager.getInstance().stopPlay();//停止播放
                mWriteLeftFl.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.bg_left_write_green));
                mRecordRightFl.setBackgroundDrawable(null);
                //-------------
                mDescribeProblemEdt.setVisibility(View.VISIBLE);
                mAudioRl.setVisibility(View.GONE);
                //-------------
                mRecordRightTxt.setTextColor(ContextCompat.getColor(this, R.color.color_report_problem_area));
                mRecordRightTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.ic_right_record_gray), null, null, null);
                //-------------
                mWriteLeftTxt.setTextColor(ContextCompat.getColor(this, R.color.white));
                mWriteLeftTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.ic_left_write), null, null, null);
                break;
            case R.id.record_right_fl://选择输入语音
                isWriteMode = false;
                //清空文字
//                mDescribeProblemEdt.setText("");

                KeyboardUtils.hideSoftInput(this);
                mWriteLeftFl.setBackgroundDrawable(null);
                mRecordRightFl.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.bg_right_audio_green));
                //-------------
                mDescribeProblemEdt.setVisibility(View.GONE);
                mAudioRl.setVisibility(View.VISIBLE);
                //-------------
                mRecordRightTxt.setTextColor(ContextCompat.getColor(this, R.color.white));
                mRecordRightTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.ic_right_record), null, null, null);
                //-------------
                mWriteLeftTxt.setTextColor(ContextCompat.getColor(this, R.color.color_report_problem_area));
                mWriteLeftTxt.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.ic_left_write_gray), null, null, null);

                break;
            case R.id.play_audio_rl://播放录音
                AudioPlayManager.getInstance().stopPlay();//停止播放
                if (isEditProblem) {
                    if (mVoiceFile == null) {
                        String voiceUrl = mProblemBean.getVoiceUrl();
                        String voiceName = voiceUrl.substring(voiceUrl.lastIndexOf("/") + 1, voiceUrl.length());
                        LogUtils.d("voice name = " + voiceName);
                        String voicePath = ConstantManager.AUDIO_SAVE_DIR + "/" + voiceName;
                        LogUtils.d("voice Path == " + voicePath);

                        mVoiceFile = new File(voicePath);
                        if (mVoiceFile.exists()) {
                            playAudio();
                        } else {
                            downloadVoice(voiceName, true);
                        }
                    } else {
                        playAudio();
                    }

                } else {
                    playAudio();
                }

                break;
            case R.id.your_location_rl:
//                if (isEditProblem) {
//                    if (mPosFile != null && mPosFile.exists()) {
//                        mLocationImgList.clear();
//                        mLocationImgList.add(new ProblemBean.ResourceBean(mPosFile.getAbsolutePath()));
//                        LocalImagePreviewActivity.start(ReportProblemActivity.this, mLocationImgList, 0);
//                    }
//                    return;
//                }
                BDLocationMapActivity.actionStart(this, mLat, mLng, mYourLocationTxt.getText().toString());
                break;
            case R.id.whether_public_rl:
                showPublicDialog();
                break;
            case R.id.save_draft_txt:
//                if (isEditProblem) {
//                    ToastUtils.showShort(getString(R.string.txt_current_is_draft));
//                    return;
//                }
//                showBackDialog();
//                showCommitDialog(true);
                doCommitProblem(true, true);
                break;
            case R.id.commit_problem_txt:
//                showCommitDialog(false);
                doCommitProblem(false, true);
                break;
            case R.id.add_picture_img:
//                if (isEditProblem) {
//                    return;
//                }
                showPictureDialog();
//                TakePhotoHelper.onClick(getTakePhoto(), false, true, true, false);
                break;
        }
    }

    /**
     * 下载语音
     *
     * @param voiceName
     */
    private void downloadVoice(String voiceName, final boolean autoPlay) {
        EasyHttp.downLoad(mProblemBean.getVoiceUrl())
                .saveName(voiceName)
                .savePath(ConstantManager.AUDIO_SAVE_DIR)
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void onStart() {
                        mPlayAudioTxt.setEnabled(false);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mPlayAudioTxt.setEnabled(true);
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                    }

                    @Override
                    public void onComplete(String path) {
                        LogUtils.d("下载语音成功");
                        mPlayAudioTxt.setEnabled(true);
                        mVoiceFile = new File(path);
                        if (autoPlay) {
                            playAudio();
                        }
                    }
                });
    }

    /**
     * 下载现场图片
     */
    private void downloadResourceImg() {
        mRecyclerView.setVisibility(View.VISIBLE);
//        mAdapter.setShowDelete(false);
        List<ProblemBean.ResourceBean> list = mProblemBean.getResourceList();
        for (ProblemBean.ResourceBean bean : list) {
            String imgUrl = bean.getContent();
            String imgName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
            LogUtils.d("imgName = " + imgName);

            File imgDir = new File(ConstantManager.PHOTO_SAVE_DIR);
            LogUtils.d("audioDir = " + imgDir.getAbsolutePath());
            String imgPath = imgDir + "/" + imgName;
            LogUtils.d("imgPath == " + imgPath);

            File imgFile = new File(imgPath);
            if (imgFile.exists()) {
                mFakeImgList.add(imgPath);
                mImgList.add(new ProblemBean.ResourceBean(imgPath));
                if (mImgList.size() >= 3) {
                    mAddPictureImg.setVisibility(View.GONE);
                }
                mAdapter.notifyItemChanged(mImgList.size() + 1);
                LogUtils.d("mImgList.size ======================== " + mImgList.size());

            } else {
                EasyHttp.downLoad(imgUrl)
                        .saveName(imgName)
                        .savePath(imgDir.getAbsolutePath())
                        .execute(new DownloadProgressCallBack<String>() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onError(ApiException e) {
                                ToastUtils.showShort(e.getMessage());
                            }

                            @Override
                            public void update(long bytesRead, long contentLength, boolean done) {
                            }

                            @Override
                            public void onComplete(String path) {
                                LogUtils.d("下载现场图片成功");
                                mFakeImgList.add(path);
                                mImgList.add(new ProblemBean.ResourceBean(path));
                                if (mImgList.size() >= 3) {
                                    mAddPictureImg.setVisibility(View.GONE);
                                }
                                mAdapter.notifyItemChanged(mImgList.size() + 1);
                                LogUtils.d("mImgList.size ==================== " + mImgList.size());
                            }
                        });
            }
        }
    }

    /**
     * 下载位置图片
     *
     * @param localImgName
     */
    private void downloadLocalImg(String localImgName) {
        File parentFile = new File(ConstantManager.LOCATION_PHOTO_SAVE_DIR);
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        EasyHttp.downLoad(mProblemBean.getLocalImgUrl())
                .saveName(localImgName)
                .savePath(parentFile.getAbsolutePath())
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                    }

                    @Override
                    public void onComplete(String path) {
                        LogUtils.d("下载位置图片成功");
                        mPosFile = new File(path);
                    }
                });
    }

    /**
     * 播放语音
     */
    private void playAudio() {
        if (mVoiceFile == null) {
            return;
        }
        LogUtils.d("playAudio == " + mVoiceFile.getAbsolutePath());

        AudioPlayManager.getInstance().stopPlay();//停止播放
        //播放录音
        AudioPlayManager.getInstance().startPlay(this, Uri.parse(mVoiceFile.getAbsolutePath()), new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1) {
                //开播（一般是开始语音消息动画）
            }

            @Override
            public void onStop(Uri var1) {
                //停播（一般是停止语音消息动画）
            }

            @Override
            public void onComplete(Uri var1) {
                //播完（一般是停止语音消息动画）
            }
        });
    }


    /**
     * 是否公开
     */
    private void showPublicDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_whether_public)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        view.findViewById(R.id.public_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mWhetherPublicTxt.setText(getString(R.string.txt_public));
                                mIsOpen = 1;
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.not_public_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mWhetherPublicTxt.setText(getString(R.string.txt_not_public));
                                mIsOpen = 0;
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }


    /**
     * 拍照
     */
    private void showPictureDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_select_picture)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        view.findViewById(R.id.camera_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mTakeHelper.onClick(getTakePhoto(), false, false, false);
//                                mAdapter.hideDelete();
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.gallery_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                                mTakeHelper.onClick(getTakePhoto(), true, false, false);

                                Matisse.from(ReportProblemActivity.this)
                                        .choose(MimeType.ofImage())
                                        .theme(R.style.Matisse_Zhihu)
                                        .countable(true)
                                        .maxSelectable(3 - numberOfImagesToSelect)
                                        .imageEngine(new GlideEngine())
                                        .forResult(REQUEST_CODE_CHOOSE);

                                dialog.cancel();

                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    /**
     * 保存到草稿箱或者提交问题的二次确认弹出框
     */
    private void showCommitDialog(final boolean isSaveDraft) {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_decision)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        TextView tipTxt = (TextView) view.findViewById(R.id.tip_txt);
                        if (isSaveDraft) {
                            tipTxt.setText(getString(R.string.txt_tip_save_draft));
                        } else {
                            tipTxt.setText(getString(R.string.txt_tip_commit_problem));
                        }
                        TextView okTxt = (TextView) view.findViewById(R.id.confirm_txt);
                        okTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //调取接口
                                long problemId = -1;
                                if (isEditProblem) {
                                    problemId = mProblemBean.getId();
                                }
                                initDialog(isSaveDraft);
                                mDisposable = mPresenter.httpCommitReport(problemId, mDesc, mAddress, mLng
                                        , mLat, mIsDraft, mIsOpen, mImgFiles, mPosFile, mVoiceFile, mVoiceTime, mProgressDialog);
                                dialog.cancel();
                            }
                        });
                        TextView noTxt = (TextView) view.findViewById(R.id.cancel_txt);
                        noTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                                finish();
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    /**
     * 是否保存草稿,点击返回弹出
     */
    private void showBackDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_back_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        TextView tipTxt = (TextView) view.findViewById(R.id.tip_txt);
//                        tipTxt.setText(getString(R.string.txt_tip_save_draft));
                        TextView okTxt = (TextView) view.findViewById(R.id.save_txt);
                        okTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                doCommitProblem(true, false);
                                dialog.cancel();
                            }
                        });
                        TextView noTxt = (TextView) view.findViewById(R.id.cancel_txt);
                        noTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    @Override
    public void onBackPressed() {
//        if(!isEditProblem)
        showBackDialog();
    }

    //----------------拍照回调接口start------------------------

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (mTakePhoto == null) {
            mTakePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return mTakePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        LogUtils.a("-------------------------takeSuccess---------------------------");
        if (result.getImages() != null && result.getImages().size() > 0) {
            String photoPath = result.getImages().get(0).getOriginalPath();
            zipPicture(photoPath);
        }
    }

    private void zipPicture(String photoPath) {
        mFakeImgList.add(photoPath);
        if (mFakeImgList.size() >= 3) {
            mAddPictureImg.setVisibility(View.GONE);
        }
        final int waterMakerRes = R.drawable.icon_water_marker;
        Flowable.just(photoPath)
                .observeOn(Schedulers.io())
                .map(new Function<String, String>() {
                    @Override
                    public String apply(@NonNull String path) throws Exception {
                        //添加水印
                        File photoFile = new File(path);
                        //小于50kb直接添加水印
                        if (photoFile.length() < 50000) {
                            String waterMarkerPath = doAddWaterMarker(photoFile.getAbsolutePath(), waterMakerRes);
                            //第二次压缩，保证添加水印的图片大小在100kb以下
                            File finalCompressFile = Luban.with(ReportProblemActivity.this)
                                    .setTargetDir(ConstantManager.PHOTO_SAVE_DIR)
                                    .get(waterMarkerPath);
                            return finalCompressFile.getAbsolutePath();
                        } else {
                            //第一次压缩，保证添加水印不会OOM
                            File file = Luban.with(ReportProblemActivity.this)
                                    .setTargetDir(ConstantManager.PHOTO_SAVE_DIR)
                                    .get(path);
                            String waterMarkerPath = doAddWaterMarker(file.getAbsolutePath(), waterMakerRes);
                            //第二次压缩，保证添加水印的图片大小在100kb以下
                            File finalCompressFile = Luban.with(ReportProblemActivity.this)
                                    .setTargetDir(ConstantManager.PHOTO_SAVE_DIR)
                                    .get(waterMarkerPath);
                            return finalCompressFile.getAbsolutePath();
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String filePath) throws Exception {
                        LogUtils.a("-------------------------添加成功---------------------------");
                        LogUtils.a("filePath： " + filePath);
                        mRecyclerView.setVisibility(View.VISIBLE);
                        ProblemBean.ResourceBean bean = new ProblemBean.ResourceBean(filePath);
                        mImgList.add(bean);
                        if (mImgList.size() >= 3) {
                            mAddPictureImg.setVisibility(View.GONE);
                        }
                        mAdapter.notifyItemChanged(mImgList.size() + 1);
                        numberOfImagesToSelect = mImgList.size();
                        LogUtils.d("select", "numberOfImagesToSelect: " + numberOfImagesToSelect);

                    }
                });
    }

    /**
     * 添加水印
     *
     * @param finalFilePath
     * @param markerResId
     * @return
     */
    public String doAddWaterMarker(String finalFilePath, int markerResId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap originBmp, finalBmp, markerBmp;
        originBmp = BitmapFactory.decodeFile(finalFilePath, options);
        int originBmpWidth = options.outWidth;
        int originBmpHeight = options.outHeight;
        options.inJustDecodeBounds = false;
        finalBmp = BitmapFactory.decodeFile(finalFilePath, options).copy(Bitmap.Config.ARGB_8888, true);
        markerBmp = BitmapFactory.decodeResource(getResources(), markerResId, options);
        int markerBmpWidth = markerBmp.getWidth();
        int markerBmpHeight = markerBmp.getHeight();
        Canvas canvas = new Canvas(finalBmp);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Rect srcRect = new Rect(0, 0, markerBmpWidth, markerBmpHeight);
        /*if (markerBmpWidth > originBmpWidth) {
            markerBmpWidth = originBmpWidth;
        }*/
        int left = originBmpWidth / 4; //- markerBmpWidth / 2 + 20;
        int top = originBmpHeight / 2 - markerBmpHeight / 2;
        Rect destRect = new Rect(left, top, left + originBmpWidth / 2, top + markerBmpHeight);
        //canvas.drawBitmap(markerBmp, left, top, paint);
        canvas.drawBitmap(markerBmp, srcRect, destRect, paint);
        paint.setColor(Color.WHITE);
        paint.setTextSize(50);
        String nowTime = TimeUtils.getNowString();
        String drawText = "";
        try {
            StringBuffer stringBuffer = new StringBuffer();
            String[] yearAndMonthAndDay = nowTime.substring(0, 10).split("-");
            for (int i = 0; i < yearAndMonthAndDay.length; i++) {
                String str = yearAndMonthAndDay[i];
                if (i == yearAndMonthAndDay.length - 1) {
                    stringBuffer.append(str);
                } else {
                    stringBuffer.append(str + ".");
                }
            }
            stringBuffer.append(" - ");
            stringBuffer.append(nowTime.substring(11, nowTime.length()));
            drawText = stringBuffer.toString();
        } catch (Exception e) {
            drawText = nowTime;
        }
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        int textHeight = fontMetrics.bottom - fontMetrics.top;
        Rect bounds = new Rect();
        paint.getTextBounds(drawText, 0, drawText.length(), bounds);
        int textWidth = bounds.right - bounds.left;

        int baseX = originBmpWidth - textWidth - 10;
        int textTop = originBmpHeight - textHeight;
        int baseY = textTop - fontMetrics.top;
        canvas.drawText(drawText, baseX, baseY, paint);
        try {
            FileOutputStream outputStream = new FileOutputStream(finalFilePath);
            if (finalBmp.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return finalFilePath;
    }

    @Override
    public void takeFail(TResult result, String msg) {
        LogUtils.a("takeFail:--------" + msg);
        ToastUtils.showLong(getString(R.string.txt_take_fail));
    }

    @Override
    public void takeCancel() {
        LogUtils.a("takeCancel:-------------");


    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ConstantManager.REQUEST_MAP_CODE) {
            if (resultCode == RESULT_OK) {
                LogUtils.d(data.toString());
                mAddress = data.getStringExtra(BDLocationMapActivity.EXTRA_LOCATION_ADDRESS);
                mYourLocationTxt.setText(mAddress);
                mLng = data.getDoubleExtra(BDLocationMapActivity.EXTRA_LOCATION_LONGITUDE, 0.0);
                mLat = data.getDoubleExtra(BDLocationMapActivity.EXTRA_LOCATION_LATITUDE, 0.0);
                String posFilePath = data.getStringExtra(BDLocationMapActivity.EXTRA_LOCATION_SNAPIMAGE_PATH);

                if (TextUtils.isEmpty(posFilePath)) {
                    ToastUtils.showShort(getString(R.string.snap_img_is_null));
                } else {
                    LogUtils.d("posFilePath = " + posFilePath);
                    //位置图片压缩
                    Flowable.just(posFilePath)
                            .observeOn(Schedulers.io())
                            .map(new Function<String, String>() {
                                @Override
                                public String apply(@NonNull String path) throws Exception {
                                    //第一次压缩
                                    File file = Luban.with(ReportProblemActivity.this)
                                            .setTargetDir(ConstantManager.LOCATION_PHOTO_SAVE_DIR)
                                            .get(path);
                                    return file.getAbsolutePath();
                                }
                            })
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<String>() {
                                @Override
                                public void accept(String filePath) throws Exception {
                                    LogUtils.d("位置图片压缩成功---------------");
                                    mPosFile = new File(filePath);
                                }
                            });
                }
                return;
            }
        } else if (requestCode == TConstant.RC_PICK_PICTURE_FROM_CAPTURE || requestCode == TConstant.RC_PICK_PICTURE_FROM_GALLERY_ORIGINAL) {
            getTakePhoto().onActivityResult(requestCode, resultCode, data);
        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<String> pathList = Matisse.obtainPathResult(data);
            for (String path : pathList) {
                LogUtils.d("select", path);
                zipPicture(path);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    //------------------拍照回调接口end----------------------

}
